package com.eastcode.base.util;

import java.beans.MethodDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ObjectConvertUtil {
	/**
	 * 对象转换成map
	 * 
	 * @param object
	 * @param marks
	 *            true 更新所有 false null不更新
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> objectToMap(Object object, boolean marks) {
		Map<String, Object> map = new HashMap<String, Object>();
		Method[] methods = object.getClass().getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			try {
				MethodDescriptor pd = new MethodDescriptor(method);
				String key = pd.getDisplayName();
				key = Character.toLowerCase(key.charAt(3)) + key.substring(4);
				if (methodName.startsWith("get")) {
					Object value = method.invoke(object);
					if (value != null && !"".equals(value)) {
						map.put(key, value);
					} else if (marks) {
						map.put(key, "");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	/**
	 * model转换成map
	 * 
	 * @param object
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> objectToMapAll(Object object) {
		return ObjectConvertUtil.objectToMap(object, true);
	}

	/**
	 * model转换成map
	 * 
	 * @param object
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> objectToMapNotNull(Object object) {
		return ObjectConvertUtil.objectToMap(object, false);
	}

	/**
	 * 利用反射填充对象
	 * 
	 * @param object
	 * @param field
	 * @param value
	 * @return
	 */
	public static Object mapToObject(Object object, Map<String, Object> resultMap) {
		return mapToObject(object, resultMap, "");
	}

	/**
	 * 排除个别的KEY值
	 * 
	 * @param object
	 * @param resultMap
	 * @param args
	 * @return
	 */
	public static Object mapToObject(Object object, Map<String, Object> resultMap, String... args) {
		try {
			Iterator<String> keys = resultMap.keySet().iterator();
			while (keys.hasNext()) {
				String field = keys.next();
				Object value = resultMap.get(field);

				boolean contains = true;
				for (int i = 0; args.length != 0 && i < args.length; i++) {
					if (field.equals(args[i].toUpperCase())) {
						contains = false;
						break;
					}
				}
				if (value != null && contains) {

					String methodName = "set" + Character.toUpperCase(field.charAt(0))
							+ field.toLowerCase().substring(1);

					Class<?> paramTypeClass = value.getClass();
					if (value instanceof java.sql.Timestamp) {
						paramTypeClass = java.util.Date.class;
					}

					Method method = object.getClass().getMethod(methodName, paramTypeClass);

					if (method != null) {
						method.invoke(object, value);
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return object;
	}
}
